package com.onileVideo.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.errorprone.annotations.Var;
import com.onileVideo.base.model.dto.pageParams;
import com.onileVideo.base.model.dto.pageResult;
import com.onileVideo.content.mapper.CourseBaseMapper;
import com.onileVideo.content.mapper.CourseCategoryMapper;
import com.onileVideo.content.mapper.CourseMarketMapper;
import com.onileVideo.content.model.dto.AddCourseDto;
import com.onileVideo.content.model.dto.CategoryDto;
import com.onileVideo.content.model.dto.CourseInfoResult;
import com.onileVideo.content.model.dto.QueryCourseParamsDto;
import com.onileVideo.content.model.po.CourseBase;
import com.onileVideo.content.model.po.CourseCategory;
import com.onileVideo.content.model.po.CourseMarket;
import com.onileVideo.content.service.CourseBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {
    @Resource
    CourseBaseMapper courseBaseMapper;
    @Resource
    CourseCategoryMapper courseCategoryMapper;
    @Resource
    CourseMarketMapper courseMarketMapper;

    @Override
    public CourseInfoResult selectCourseById(Integer id){
        CourseInfoResult result = new CourseInfoResult();
        CourseBase courseBase = courseBaseMapper.selectById(id);
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        BeanUtils.copyProperties(courseBase, result);
        BeanUtils.copyProperties(courseMarket, result);
        return result;
    }


    //分页+条件 查询课程信息
    @Override
    public pageResult<CourseBase> list(QueryCourseParamsDto queryCourseParamsDto, pageParams pageParams) {
        pageResult<CourseBase> result = new pageResult<>();
        //将数据分页处理
        //当前页
        int pageNum = pageParams.getPageNo().intValue();
        //要查询多少条数据
        int pageSize = pageParams.getPageSize().intValue();
//        PageHelper.startPage(pageNum, pageSize);
        Page<CourseBase> pageInfo = new Page<>(pageNum, pageSize);
        //在数据库条件查询所有数据
        courseBaseMapper.selectAllWithCondition(pageInfo, queryCourseParamsDto);
        //获取分页对象
//        PageInfo<CourseBase> pageInfo = new PageInfo<>(courses);
        //封装结果
        result.setItems(pageInfo.getRecords());
        result.setPage(pageInfo.getCurrent());
        result.setCounts(pageInfo.getTotal());
        result.setPageSize(pageInfo.getSize());
        return result;
    }

    //查询所有课程目录(数据库为树形结构 返回结果也是树形结构)
    public List<CategoryDto> queryBaseCategory(){
        //查询出所有分类数据
        QueryWrapper<CourseCategory> wrapper = new QueryWrapper<>();
        List<CourseCategory> list = courseCategoryMapper.selectList(wrapper);
        //准备map(该map可以快速找到某个节点对应的父节点)
        HashMap<String, CategoryDto> map = new HashMap<>();
        for (CourseCategory category : list) {
            String nodeId = category.getId();
            CategoryDto categoryDto = new CategoryDto();
            BeanUtils.copyProperties(category, categoryDto);
            categoryDto.setChildrenTreeNodes(null);
            map.put(nodeId, categoryDto);
        }
        map.put("0", new CategoryDto());
        //遍历 建立所有节点之间的关系
        //先创建一个根节点
        CategoryDto root = new CategoryDto();
        for (CourseCategory category : list) {
            //节点本身
            CategoryDto node = map.get(category.getId());
            if(category.getParentid().equals("1")){
                root.addChildren(node);
            }
            else{
                //父节点
                CategoryDto parentNode = map.get(category.getParentid());
                //将本节点加入到父节点的list中
                parentNode.addChildren(node);
            }
        }
        return root.getChildrenTreeNodes();
    }

    @Override
    public CourseInfoResult insertCourse(Long companyId, AddCourseDto addCourseDto) {
        CourseBase courseBase = new CourseBase();
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto, courseBase);
        BeanUtils.copyProperties(addCourseDto, courseMarket);
        //课程基本信息填充
        // 2.1 设置默认审核状态（去数据字典表中查询状态码）
        courseBase.setAuditStatus("202002");
        // 2.2 设置默认发布状态
        courseBase.setStatus("203001");
        // 2.3 设置机构id
        courseBase.setCompanyId(companyId);
        // 2.4 设置添加时间
        courseBase.setCreateDate(LocalDateTime.now());
        //写入db
        int insertCount = courseBaseMapper.insert(courseBase);
        //课程营销信息填充
        if(insertCount < 1) throw new RuntimeException("课程添加失败");
        Long courseBaseId = courseBase.getId();
        courseMarket.setId(courseBaseId);
        //如果课程是收费的 那价格必须大于0
        if ("201001".equals(courseMarket.getCharge())) {
            if (courseMarket.getPrice() == null || courseMarket.getPrice() < 0) {
                throw new RuntimeException("收费课程价格必须大于0");
            }
        }
        //保存到db
        int marketCount = courseMarketMapper.insert(courseMarket);
        if (marketCount < 1) throw new RuntimeException("课程添加失败");
        return getCourseInfoResult(courseBase.getId());
    }

    private CourseInfoResult getCourseInfoResult(Long id) {
        CourseInfoResult courseInfoResult = new CourseInfoResult();
        CourseBase courseBase = courseBaseMapper.selectById(id);
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        if (courseBase == null || courseMarket == null) {
            throw new RuntimeException("课程添加失败");
        }
        //填充信息
        BeanUtils.copyProperties(courseBase, courseInfoResult);
        BeanUtils.copyProperties(courseMarket, courseInfoResult);
        //填充 大分类名字
        String mt = courseBase.getMt();
        String mtName = courseCategoryMapper.selectById(mt).getName();
        courseInfoResult.setMtName(mtName);
        //填充 小分类名字
        String st = courseBase.getSt();
        String stName = courseCategoryMapper.selectById(st).getName();
        courseInfoResult.setStName(stName);
        return courseInfoResult;
    }




}
